package com.warm.spring.asyn;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @Date: 2020/3/31 16:49
 * @Author: LChuang
 * @Description:
 */
@RestController
@RequestMapping("/asyn")
public class AsynController {

    @Autowired
    AsynService asynService;

    @GetMapping("/movies")
    public String completableFutureTask(){
        // start time
        long start = System.currentTimeMillis();
        // executor max tread asynTask
        List<String> words = Arrays.asList("F", "T", "S", "Z", "J", "C");
        List<CompletableFuture<List<String>>> completableFutureList = words.stream()
                .map(word ->
                        asynService.completableFutureTask(word)
                )
                .collect(Collectors.toList());
        // CompletableFuture.join（）方法可以获取他们的结果并将结果连接起来
        List<List<String>> results = completableFutureList.stream().map(CompletableFuture::join).collect(Collectors.toList());
        // 打印结果以及运行程序运行花费时间
        System.out.println("Elapsed time: " + (System.currentTimeMillis() - start));

        long start1 = System.currentTimeMillis();
        words.stream().forEach(word -> asynService.completableFutureTask1(word));
        System.out.println("Elapsed time1: " + (System.currentTimeMillis() - start1));
        return results.toString();
    }
}
